﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Helpers;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Eneta.Portal.NewsAndBlogs.Controls
{
    public class AnnouncementListControl  :UserControl
    {
        protected Repeater postsRepeater;

        protected HtmlGenericControl pager;
        protected HtmlGenericControl pagerPrevContainer;
        protected HtmlGenericControl pagerNextContainer;
        protected HtmlAnchor pagerPrevLink;
        protected HtmlAnchor pagerNextLink;

        protected HtmlGenericControl pagerBottom;
        protected HtmlGenericControl pagerBottomPrevContainer;
        protected HtmlGenericControl pagerBottomNextContainer;
        protected HtmlAnchor pagerBottomPrevLink;
        protected HtmlAnchor pagerBottomNextLink;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            postsRepeater.ItemDataBound += PostsRepeaterItemDataBound;
        }

        protected void PostsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var announcement = (AnnouncementDto)e.Item.DataItem;

            var blogNameLink = (HtmlAnchor)e.Item.FindControl("blogNameField");
            if (announcement.OwnerUserName == announcement.InfoSourceName) //dirty hack to hide source name
                blogNameLink.Visible = false;
            blogNameLink.InnerText = announcement.InfoSourceName;
            blogNameLink.HRef = announcement.InfoSourceUrl;

            var postDateField = (HtmlContainerControl)e.Item.FindControl("postDateField");
            postDateField.InnerText = announcement.Created.Date.ToShortDateString();

            var summaryField = (Label)e.Item.FindControl("summaryField");
            announcement.Body = RegExHelper.RemoveHtmlTags(announcement.Body);
            if (announcement.Body.Length <= 255)
                summaryField.Text = announcement.Body;
            else
                summaryField.Text = announcement.Body.Substring(0, 255);


            var profileRepository = new UserProfileRepository(SPContext.Current.Web);
            var profile = profileRepository.GetUserProfileById(announcement.OwnerProfileId);
            var profileImage = (HtmlImage) e.Item.FindControl("profileImage");
            profileImage.Src = profile.UserImage32x32Url;

            var authorLink = (HtmlAnchor)e.Item.FindControl("authorField");
            authorLink.HRef = EnetaApplication.PortalProfilePageUrl + "?profileID=" + profile.Id;

            var profileLink = (HtmlAnchor)e.Item.FindControl("profileLink");
            profileLink.HRef = authorLink.HRef;

            var keywordsRepeater = (Repeater)e.Item.FindControl("keywordsRepeater");
            keywordsRepeater.ItemDataBound += KeywordsRepeaterItemDataBound;
            keywordsRepeater.DataSource = announcement.Keywords;
            keywordsRepeater.DataBind();
        }

        protected void KeywordsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var keyword = (KeywordDto)e.Item.DataItem;
            var keywordTitle = (HtmlGenericControl)e.Item.FindControl("tagLink");
            keywordTitle.InnerText = keyword.Title;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                var repository = new AnnouncementRepository(EnetaApplication.PortalAnnouncementsSiteUrl);

                if (!string.IsNullOrEmpty(Request.QueryString["rss"]))
                {
                    Response.Clear();
                    Response.ContentType = "application/rss+xml";
                    Response.Write(repository.GetAnnouncementsRss());
                    Response.End();
                    return;
                }
                if (!string.IsNullOrEmpty(Request.QueryString["commentsrss"]))
                {
                    Response.Clear();
                    Response.ContentType = "application/rss+xml";
                    Response.Write(repository.GetCommentsRss());
                    Response.End();
                    return;
                }

                var posts = GetPosts();

                if (posts.Count > 0)
                {
                    //BindFirstPost(posts[0]);
                    //posts.RemoveAt(0);
                }

                postsRepeater.DataSource = posts;
                postsRepeater.DataBind();


                var master = Page.Master;
                if (master != null)
                {
                    var link = (HtmlLink)master.FindControl("rssMetaUrl");
                    if (link != null)
                    {
                        link.Attributes["title"] = EnetaApplication.PortalTitle + ": " + GetResourceString("AnnouncementsTitle");
                        link.Attributes["href"] = EnetaApplication.PortalAnnouncementsFeedBurnerUrl;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogWarning("OnLoad(): Error occured");
                Logger.LogException(ex);
            }
        }

        protected IList<AnnouncementDto> GetPosts()
        {
            var currentPage = Request.ServerVariables["PATH_INFO"];
            var rep = new AnnouncementRepository(EnetaApplication.PortalAnnouncementsSiteUrl);

            var page = 1;
            var pageSize = 10;
            int.TryParse(Request.QueryString["page"], out page);
            if (page < 1)
                page = 1;

            var posts = rep.GetApprovedAnnouncements(page, pageSize);

            if (Math.Max(1, page - 1) == 1)
                pagerPrevLink.HRef = currentPage;
            else
                pagerPrevLink.HRef = currentPage + "?page=" + Math.Max(1, page - 1);
            pagerBottomPrevLink.HRef = pagerPrevLink.HRef;

            if (Math.Min(posts.PageCount, page + 1) == 1)
                pagerNextLink.HRef = currentPage;
            else
                pagerNextLink.HRef = currentPage + "?page=" + Math.Min(posts.PageCount, page + 1);
            pagerBottomNextLink.HRef = pagerNextLink.HRef;

            if (page <= 1)
                pagerPrevContainer.Visible = false;
            if (page >= posts.PageCount)
                pagerNextContainer.Visible = false;

            pagerBottomPrevContainer.Visible = pagerPrevContainer.Visible;
            pagerBottomNextContainer.Visible = pagerNextContainer.Visible;

            return posts.Results;
        }
        private object GetResourceString(string label)
        {
            var resourceString = "$Resources:NewsAndBlogs," + label;
            var result = SPUtility.GetLocalizedString(resourceString, "NewsAndBlogs", SPContext.Current.Web.Language);
            return result;
        }
    }
}